<?php
namespace Buu\Modules\Zabbix\Lib;

use ZabbixApi\ZabbixApi;
use ZabbixApi\Exception;
use Buu\Lib\Util;

class ZabbixService{
	const WXROBOT_URL = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=9ec4c281-5266-4cd5-bbc6-9d17bba6185b';
	const ZABBIX_URL = 'https://vzbx.haohaozhu.me/api_jsonrpc.php';
	const ZABBIX_USER = 'xinshaopu';
	const ZABBIX_PASSWORD = 'b0e6a3r0';
	private $zbx;
	public function __construct(){
		$this->zbx = new ZabbixApi(self::ZABBIX_URL, self::ZABBIX_USER, self::ZABBIX_PASSWORD);
	}

	public function statAlertsYesterday(){
		$params = array(
			'time_from' => time()-86400,
			'limit' => 10000
		);
		$rs = $this->zbx->alertGet($params);
		

		if(count($rs) > 0){
			$alertList = [];
			foreach ($rs as $row) {
				//用报警第一行为特征
				$tmp = explode("\n" , $row->message);
				$hz_groups = $this->get_hzgroup($row->message);
				$alert_msg_type = trim($tmp[0]);
				foreach($hz_groups as $hzgroup){
					//替换到服务器名中的编号，只保留类型比如 hhz_statweb。
					preg_match('/(hzv_[^ ]+)[0-9]+/' , $alert_msg_type , $b);
					$alertList[$hzgroup][] = str_replace($b[0] ,$b[1] , $alert_msg_type);
				}
			}

			$msg .= "[buu]24小时内zabbix报警统计\n";
			foreach ($alertList as $hzgroup => $Lists) {
				
				$msg .= "@@@ hzgroup:".$hzgroup." 共".count($Lists)."次：\n";
				
				$alertListGroup = array_count_values($Lists);
				arsort($alertListGroup);
				foreach ($alertListGroup as $alert => $times) {
					$msg .= '('.$times.'次) '.$alert."\n";
				}
			}
			

			Util::wxRobotMsg(self::WXROBOT_URL ,$msg);
		}
	}
	function get_hzgroup($message){
        preg_match('/hzgroup:([a-z0-9]+)/' , $message , $b);
        $hz_groups = array_unique(array($b[1]));
        return count($hz_groups) > 0 ? $hz_groups : array('default');
	}
}